package ui.helpers;

import core.Database;
import core.DatabaseTable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import ui.ApplicationWindow;
import ui.TableActionsPanel;

/**
 *
 * @author Sakis Vtdk <sakis.vtdk@gmail.com>
 */
public class EditTableListener implements ActionListener
{
	@Override
	public void actionPerformed(ActionEvent e) 
	{
		//get the source (i.e. button)
		JButton button = (JButton) e.getSource();

		//get the parent of the button (i.e. the form) to have access to the components
		TableActionsPanel tableActionsPanel = (TableActionsPanel) button.getParent();

		DatabaseTable tbl = tableActionsPanel.getTable();

		//handle renaming
		//if the table name has been changed
		if(!tableActionsPanel.getNameTextFieldText().equals(tbl.getName()))
		{
			try
			{
				Database db = Database.getDatabase();
				db.renameTable(tbl.getId(), tableActionsPanel.getNameTextFieldText());
			}
			catch(Exception exc)
			{
				JOptionPane.showMessageDialog(null, "There is already a table named '"+ tableActionsPanel.getNameTextFieldText() +"'. Try another", "Error!", JOptionPane.ERROR_MESSAGE);
			}
		}

		ApplicationWindow.getApplicationWindow().refreshItems();
		
	}
	// <editor-fold desc="Getters">

	// </editor-fold>


	// <editor-fold desc="Setters">

	// </editor-fold>


	// <editor-fold desc="Private variables">

	// </editor-fold>

}
